package org.yelongframework.core.resource.web;

import java.io.InputStream;
import java.util.Objects;

import javax.servlet.ServletContext;

import org.yelongframework.commons.lang.StringUtil;
import org.yelongframework.core.resource.AbstractScopeResourceSupplier;
import org.yelongframework.lang.Nullable;

/**
 * 简单的WEB范围资源供应商
 * 
 * @since 1.0.0
 */
public class SimpleWebScopeResourceSupplier extends AbstractScopeResourceSupplier implements WebScopeResourceSupplier {

	// ==================================================构造器==================================================

	/**
	 * @param urlMapping        URL映射
	 * @param resourceScopePath 资源范围路径 默认为 /
	 */
	public SimpleWebScopeResourceSupplier(@Nullable String urlMapping, @Nullable String resourceScopePath) {
		super(urlMapping, resourceScopePath);
	}

	// ==================================================获取资源流==================================================

	@Override
	public InputStream getResourceAsStream(ServletContext servletContext, String resourcePath, boolean urlMapping) {
		Objects.requireNonNull(resourcePath);
		if (urlMapping && this.urlMapping != null) {
			if (resourcePath.startsWith(this.urlMapping)) {
				resourcePath = resourcePath.substring(this.urlMapping.length());
			}
		}
		String resourceScopePath = StringUtil.deleteEndsSlash(this.resourceScopePath);
		resourcePath = StringUtil.appendStartsSlash(resourcePath);
		return servletContext.getResourceAsStream(resourceScopePath + resourcePath);
	}

}
